package ginresult

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"sync"
)

var jsonResultPool *sync.Pool


func init()  {
	jsonResultPool = &sync.Pool{
		New: func()  interface{}{
			return &JsonResult{}
		},
	}
}

type JsonResult struct {
	Code int `json:"code"`
	Msg string `json:"msg"`
	Result interface{} `json:"result"`
}
var err error
type ErrorCustom struct {
	HttpCode int
	BusinessCode int
	Err error
}

func NewErrorCustom(httpCode int, businessCode int, err error) *ErrorCustom {
	return &ErrorCustom{HttpCode: httpCode, BusinessCode: businessCode, Err: err}
}



func (e ErrorCustom)Error() string{
	return e.Err.Error()
}

type OutputFunc func(ctx *gin.Context,v interface{})
type ResultFunc func(code int,msg string,result interface{}) func(output OutputFunc)
type ResultOKFunc func(result interface{}) func(output OutputFunc)
type ResultErrorFunc func(result interface{}) func(output OutputFunc)

func R(c* gin.Context) ResultFunc  {

	return func(code int, msg string, result interface{}) func(output OutputFunc) {
		r := jsonResultPool.Get().(*JsonResult)

		r.Msg = msg
		r.Code = code
		r.Result = result

		return func(output OutputFunc) {
			defer jsonResultPool.Put(r)
			output(c,r)
		}
	}


}

func R_OK(c* gin.Context) ResultOKFunc  {

	return func(result interface{}) func(output OutputFunc) {
		r := jsonResultPool.Get().(*JsonResult)

		r.Msg = "success"
		r.Code = C_S_OK
		r.Result = result

		return func(output OutputFunc) {
			defer jsonResultPool.Put(r)
			output(c,r)
		}
	}


}

func R_ERROR(c* gin.Context) ResultErrorFunc  {

	return func(result interface{}) func(output OutputFunc) {
		r := jsonResultPool.Get().(*JsonResult)

		r.Msg = "failed"
		r.Code = C_E_BADREQUEST
		r.Result = result

		return func(output OutputFunc) {
			defer jsonResultPool.Put(r)
			output(c,r)
		}
	}


}
//没有授权登陆
func R_NOAUTH(c* gin.Context) ResultErrorFunc  {

	return func(result interface{}) func(output OutputFunc) {
		r := jsonResultPool.Get().(*JsonResult)

		r.Msg = "forbidden"
		r.Code = C_E_FORBIDDEN
		r.Result = result

		return func(output OutputFunc) {
			defer jsonResultPool.Put(r)
			output(c,r)
		}
	}


}

func OKJson(ctx *gin.Context,v interface{})  {
	ctx.JSON(http.StatusOK,v)
}
func ErrorJson(ctx *gin.Context,v interface{})  {
	ctx.JSON(http.StatusBadRequest,v)
}
func ForbiddenJson(ctx *gin.Context,v interface{})  {
	ctx.JSON(http.StatusForbidden,v)
}